/* axios 配置 */
import axios, { AxiosRequestConfig, AxiosResponse, AxiosRequestHeaders } from 'axios'
import { TokenHandler } from '@/utils/token'
import { router } from '@/modules/router'
import { ElMessage } from 'element-plus'
import _ from 'lodash'

// 创建axios的实例
const service = axios.create({
  baseURL: 'http://10.1.2.90:5700',
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
    'Set-Cookie': 'HttpOnly;Secure;SameSite=None',
  },
  withCredentials: true, // 跨域请求时是否需要使用凭证
  timeout: 30000,
})

// 添加请求拦截器
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    if (config.url !== '/sso-token') {
      let token = TokenHandler.getToken()
      if (token && config.headers) {
        config.headers.Authorization = token
      } else {
        const CancelToken = axios.CancelToken
        config.cancelToken = new CancelToken(function (cancel) {
          // router.push('/login')
          console.log('跳转登录界面')
        })
      }
    }
    return config
  },
  (error: any) => {
    // console.log('发送请求错误', error.response, error.data);
    // 错误抛到业务代码
    error.data = {
      message: '服务器异常，请联系管理员!',
    }
    return Promise.reject(error)
  }
)

//添加响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    /* 处理 http 错误，抛到业务代码 */
    let { status, data, config } = response
    if (status < 200 || status >= 300) {
      const message = showStatus(status)
      ElMessage({
        message,
        type: 'error',
        showClose: true,
      })
      data.message = message
      return Promise.reject(data)
    }
    if (data.code === 10000) {
      let url = config.url
      let bool = _.indexOf(['/sso-token', '/refresh-ssotoken'], config.url) === -1
      return bool ? data.data : data
    }
    return response.data
  },
  (error: any) => {
    return Promise.reject(error)
  }
)
const showStatus = (status: number) => {
  let message = ''
  switch (status) {
    case 400:
      message = '请求错误(400)'
      break
    case 401:
      message = '未授权，请重新登录(401)'
      console.warn('401跳转登录界面')
      // return router.push('/login')
      break
    case 403:
      message = '拒绝访问(403)'
      break
    case 404:
      message = '请求出错(404)'
      break
    case 408:
      message = '请求超时(408)'
      break
    case 500:
      message = '服务器错误(500)'
      break
    case 501:
      message = '服务未实现(501)'
      break
    case 502:
      message = '网络错误(502)'
      break
    case 503:
      message = '服务不可用(503)'
      break
    case 504:
      message = '网络超时(504)'
      break
    case 505:
      message = 'HTTP版本不受支持(505)'
      break
    default:
      message = `连接出错(${status})!`
  }
  return message
  // return `${message}，请检查网络或联系管理员!`
}

export default service
